﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using LIK.WakeOnLan.Forms;

namespace LIK.WakeOnLan.Code
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //load required assemblies from embeded resources 
            AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }

        static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
        {
            try
            {           
                //Получаем текущую сборку которая выполняется(чтобы из нее брать ресурсы)
                Assembly thisAssembly = Assembly.GetExecutingAssembly();
                //Compose resource name
                var dllName = args.Name.Substring(0, args.Name.IndexOf(',')).ToLower().Replace(".resources", "") + ".dll";
                var name = args.Name.Substring(0, args.Name.IndexOf(',')).ToLower().Replace(".resources", "");
                var thisAssemblyName = Path.GetFileNameWithoutExtension(thisAssembly.Location);
                if (thisAssemblyName.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return args.RequestingAssembly;
                }
                //Get resource by name
                var resourceName = thisAssembly.GetManifestResourceNames().First(s => s.EndsWith(dllName, StringComparison.OrdinalIgnoreCase));

                using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName))
                {
                    //Read resource into byte array
                    byte[] block = new byte[stream.Length];
                    stream.Read(block, 0, block.Length);
                    //Load assembly from byte array into current application domain and return it
                    return Assembly.Load(block);
                }
            }
            catch(Exception ex)
            {
                return null;
            }
        }


    }
}
